package com.dayu.tcp.common.util;

import lombok.SneakyThrows;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

public class AddressUtil {
    private AddressUtil() {
    }

    /**
     * 得到本机ip地址
     *
     * @return 示例:192.168.12.123
     */
    @SneakyThrows
    public static String getLocalIP() {
        InetAddress address = InetAddress.getLocalHost();
        return address.getHostAddress();
    }

    /**
     * 将IP地址转换为 SocketAddress，以spilt分割，spilt不能为 ":"和"."
     *
     * @param addressArray 示例1：192.168.12.123:8080
     *                     示例2：192.168.12.123:8080,192.168.12.124:8081
     * @return SocketAddress[]
     */
    public static SocketAddress[] parseAddress(String addressArray, String spilt) {
        if (StrUtil.isEmpty(addressArray)) {
            throw new IllegalArgumentException("addressArray can not be null or empty.");
        }
        if (":".equals(spilt) || ".".equals(spilt)) {
            throw new IllegalArgumentException("spilt can not be ':' or '.'.");
        }
        String[] array = addressArray.split(spilt);
        SocketAddress[] ret = new SocketAddress[array.length];
        for (int i = 0; i < array.length; i++) {
            String address = array[i];
            String[] parts = address.split(":");
            if (parts.length == 2) {
                ret[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
            } else {
                throw new IllegalArgumentException("address " + address + " is invalid.");
            }
        }
        return ret;
    }

    public static SocketAddress[] parseAddress(String addressArray) {
        return parseAddress(addressArray, ",");
    }

    /**
     * 将字符串形式的port转为int形式，以spilt分割
     *
     * @param portArray 示例1：8080
     *                  示例2：8080,8081
     * @return int[]
     */
    public static int[] parsePort(String portArray, String spilt) {
        if (StrUtil.isEmpty(portArray)) {
            throw new IllegalArgumentException("portArray can not be null or empty.");
        }
        String[] array = portArray.split(spilt);
        int[] ret = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            ret[i] = Integer.parseInt(array[i].trim());
        }
        return ret;
    }

    public static int[] parsePort(String portArray) {
        return parsePort(portArray, ",");
    }
}
